cmake_minimum_required(VERSION 3.20)

if (NOT DEFINED CMAKE_TOOLCHAIN_FILE)
    set(CMAKE_TOOLCHAIN_FILE "./cmake/c51.toolchain.cmake" CACHE PATH "toolchain file")
endif ()

project(main C)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

if (LINUX)
  set(C51 "/usr/share/sdcc")
else()
  set(C51 "/opt/local/share/sdcc")
endif()

if (NOT C51)
    message(FATAL_ERROR "C51 environment variable is not set")
endif ()

include_directories("${C51}/include" "include")

file(GLOB_RECURSE SOURCES "${PROJECT_SOURCE_DIR}/src/*.c")

add_executable(${PROJECT_NAME} ${SOURCES})

if (LINUX)
  add_custom_command(TARGET ${PROJECT_NAME}
      POST_BUILD
      WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
      COMMAND ${CMAKE_OBJCOPY} ARGS -O ihex -R .eeprom -R .fuse -R .lock -R .signature ${PROJECT_NAME}.ihx ${PROJECT_NAME}.hex
  )
else()
  add_custom_command(TARGET ${PROJECT_NAME}
      POST_BUILD
      WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
      COMMAND packihx ${PROJECT_NAME}.ihx > ${PROJECT_NAME}.hex
  )
endif()

